package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
)

type CalculationRequest struct {
	Num1     float64 `json:"num1"`
	Num2     float64 `json:"num2"`
	Operator string  `json:"operator"`
}

func calculateHandler(w http.ResponseWriter, r *http.Request) {
	// log.Printf("收到请求: %s %s", r.Method, r.URL.Path)
	// 允许跨域请求
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
    w.Header().Set("Access-Control-Allow-Headers", "Content-Type")

	if r.Method == http.MethodOptions {
        return
    }

	// 非 option 请求继续处理
	if r.Method != http.MethodPost {
		http.Error(w, "只支持 POST 请求", http.StatusMethodNotAllowed)
		return
	}

	var req CalculationRequest
	err := json.NewDecoder(r.Body).Decode(&req)
	if err != nil {
		http.Error(w, "请求体解析错误", http.StatusBadRequest)
		return
	}

	// log.Printf("收到计算请求: num1 = %.2f, num2 = %.2f, operator = %s", 
	// 		req.Num1, req.Num2, req.Operator)

	var result float64
	switch req.Operator {
	case "+":
		result = req.Num1 + req.Num2
	case "-":
		result = req.Num1 - req.Num2
	case "*":
		result = req.Num1 * req.Num2
	case "/":
		if req.Num2 == 0 {
			http.Error(w, "除数不能为零", http.StatusBadRequest)
			return
		}
		result = req.Num1 / req.Num2
	default:
		http.Error(w, "不支持的运算符", http.StatusBadRequest)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(map[string]float64{"result": result})
}

func main() {
	http.HandleFunc("/calculate", calculateHandler)
	fmt.Println("服务器启动，监听端口 8080")
	log.Fatal(http.ListenAndServe(":8080", nil))
}
